
#include "simulator.h"
#include "undertopomgr.h"
#include "config.h"
#include "peerloger.h"
#include "scheduler.h"
#include "chordgod.h"
#include "random.h"


int main (int argc, char const* argv[])
{
	if ( argc!=2 ){
		fprintf( stderr, "Invalid parameters.\nUsage: %s config_file\n", argv[0] );
		return(1);
	}
	//initialization
	if ( !config.init(argv[1]) ){
		fprintf( stderr, "Config init failed\n" );
		return 1;
	}

	if ( !rng.init() ){
		fprintf( stderr, "Random number generator init failed\n" );
		return 1;
	} else{
		fprintf( stderr, "Using seed:%ld\n", rng.getSeed() );
	}

	if ( !Simulator::create() ){
		fprintf( stderr, "Create Simulator failed\n" );
		return 1;
	}

	if ( !PeerLoger::create() ){
		fprintf( stderr, "Create PeerLoger failed\n" );
		return 1;
	}
	if ( !PeerLoger::instance().init() ){
		fprintf( stderr, "PeerLoger init failed\n" );
		return 1;
	}

	if ( !UnderTopoMgr::create() ){
		fprintf( stderr, "Create UnderTopoMgr failed\n" );
		return 1;
	}
	if ( !UnderTopoMgr::instance().init() ){
		fprintf( stderr, "UnderTopoMgr init failed\n" );
		return 1;
	}

	if ( !ChordGod::create() ){
		fprintf( stderr, "Create ChordGod failed\n" );
		return 1;
	}
	if ( !ChordGod::instance().init() ){
		fprintf( stderr, "ChordGod init failed\n" );
		return 1;
	}
	if ( !ChordGod::instance().initChord() ){
		fprintf( stderr, "ChordGod peers have not been initialized\n" );
	}

	if ( !Scheduler::create() ){
		fprintf( stderr, "Create Scheduler failed\n" );
		return 1;
	}
	if ( !Scheduler::instance().scheduleAll() ){
		fprintf( stderr, "Scheduler::scheduleNodes failed\n" );
		return 1;
	}

	//kick off
	Simulator::instance().run();

	//destroy objects
	Scheduler::destroy();
	ChordGod::destroy();
	UnderTopoMgr::destroy();
	PeerLoger::destroy();
	Simulator::destroy();

	fprintf(stderr, "finished\n");
	return 0;
}

